package org.kazuhiko.rpg.client.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.kazuhiko.rpg.client.net.packet.PacketDefinition;
import org.kazuhiko.rpg.client.net.packet.PacketField;
import org.kazuhiko.rpg.client.net.packet.PacketManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public final class PersistenceManager
{	
	private static final Logger logger = LoggerFactory.getLogger( PersistenceManager.class );
	
	private static final PersistenceManager instance = new PersistenceManager();
	
	private final XStream xstream = new XStream( new DomDriver() );
	
	public static PersistenceManager getPersistenceManager()
	{		
		return instance;
	}
	
	private PersistenceManager()
	{
		xstream.alias( "packets", PacketManager.class );
		xstream.alias( "packet", PacketDefinition.class );
		xstream.alias( "field", PacketField.class );
	}
	
	public Object load( String file )
	{
		logger.trace( "Loading from {}", file );
		
		Object ret;
		
		try
		{
			ret = xstream.fromXML( new FileInputStream( file ) );
		}
		catch( FileNotFoundException ex )
		{
			throw new RuntimeException( ex );
		}
		
		return ret;
	}
	
	public void save( String file, Object o )
	{
		try
		{
			xstream.toXML( o, new FileOutputStream( file ) );
		}
		catch( FileNotFoundException ex )
		{
			throw new RuntimeException( ex );
		}
	}
	
	public XStream getXStream()
	{
		return xstream;
	}
}
